import storage from '@/utils/storage';
import config from '@/config'

const state = {
	totalConfig: config, //全部配置
	areaConfig: null, //当前选择的区域的配置
	selectedArea: uni.getStorage('selectedArea'), //当前选择的区域
}

const mutations = {
	SET_CONFIG(state, totalConfig) {
		state.totalConfig = totalConfig
	},
	SET_SELECTED_AREA(state, key) {
		state.selectedArea = key
	},
	SET_AREA_CONFIG(state, area) {
		state.areaConfig = area;
	},
}

const actions = {
	//设置全部配置到state-config
	setConfig({
		commit
	}, totalConfig) {
		commit('SET_CONFIG', totalConfig)
	},
	//设置当前区域到state-selectedArea，同时设置当前区域配置到state-areaConfig
	setSelectedArea({
		state,
		commit
	}, key) {
		commit('SET_SELECTED_AREA', state.totalConfig[key], key)
		commit('SET_AREA_CONFIG', state.totalConfig[key])
	},
	initAreaConfig({
		state,
		commit
	}, key) {
		commit('SET_AREA_CONFIG', state.totalConfig[key])
	},
	//切换区域
	selectArea({
		dispatch,
		state
	}, key, isSaveStorage = true) {
		if (state.totalConfig[key]) {
			dispatch('setSelectedArea', key)
			if (isSaveStorage) {
				storage.set('selectedArea', key) //保存到本地
			}
		} else {
			console.log('没有找到该区域配置');
		}
	}
}

export default {
	state,
	mutations,
	actions
}